package com.fare.taluo.core.domain.entity.pretreatment;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.persistence.Column;
import javax.persistence.Table;

import org.apache.commons.lang3.time.DateUtils;
import org.hibernate.annotations.Where;
import org.springframework.transaction.annotation.Transactional;

import com.dayatang.domain.InstanceFactory;
import com.fare.taluo.GlobalsConst;
import com.fare.taluo.core.domain.config.city.PortEntity;
import com.fare.taluo.core.domain.config.line.FlightInfoEntity;
import com.fare.taluo.core.domain.hibernate.QueueBasicDataRepositoryImpl;
import com.fare.taluo.core.domain.queue.QueueBaseEntity;
import com.fare.taluo.core.domain.queue.QueueBaseRepository;
import com.fare.taluo.core.domain.thread.CELineThread;
import com.fare.taluo.core.domain.thread.CSAirLineThread;
import com.fare.taluo.core.domain.thread.HNLinePdfParseThread;
import com.fare.taluo.core.domain.thread.ZHLinePdfParseThread;
import com.fare.taluo.crawl.CrawlConst;
import com.foreveross.threadpool.queue.WorkQueue;

@javax.persistence.Entity
@Table(name="que_port_data")
@Where(clause="flg_deleted=0")
public class QueueLineEntity extends QueueBaseEntity<QueueLineEntity>{

	/**
	 * 
	 */
	private static final long serialVersionUID = 5054745706268789574L;
    
	@Column(name = "FROMCITY")
	private String fromCity;
	
	@Column(name = "TOCITY")
	private String toCity;
	public static int ceairRemain = CrawlConst.CRAWL_LINE_CEAIR;//统计剩下的抓取次数
	public static int csairRemain = CrawlConst.CRAWL_LINE_CSAIR;//同上
	public static int feiRemain = CrawlConst.CRAWL_FEI_CHANG_ZHUN;//同上
	

	@Override
	protected QueueBaseRepository<QueueLineEntity> getEntityRepository() {
		return InstanceFactory.getInstance(QueueBasicDataRepositoryImpl.class);
	}

	@Override
	public QueueBaseEntity<QueueLineEntity> createNextTask(Long id)
			throws Exception {
		// 根据id获得对象
		QueueLineEntity entity = super.getBaseEntityRepository().get(
				QueueLineEntity.class, id);

    			QueueLineEntity newEntity = new QueueLineEntity();
				newEntity.setCreateTime(new Date());
				newEntity.setCreator(entity.getCreator());
				newEntity.setCreatorName(entity.getCreatorName());
				newEntity.setFromCity(entity.getFromCity());
				newEntity.setEndTime(entity.getEndTime());
				newEntity.setLoadTime(entity.getLoadTime());
				newEntity.setName(entity.getName());
			    newEntity.setToCity(entity.getToCity());
				newEntity.setFlgDeleted(GlobalsConst.FLG_NO);
				if (entity.getName().startsWith("(自动频率创建)")) {
					newEntity.setName(entity.getName());
				} else {
					newEntity.setName("(自动频率创建)" + entity.getName());
				}
				newEntity.setStatus(WorkQueue.STATUS_WAITING);
				// 根据频率设置下一个任务的计划开始时间
				newEntity.setPlanStartTime(DateUtils.addHours(
						entity.getPlanStartTime(), 12));
				if (newEntity.getPlanStartTime().before(new Date())) {
					newEntity.setPlanStartTime(DateUtils
							.addHours(new Date(), 12));
				}
				super.getBaseEntityRepository().save(newEntity);
				return newEntity;
	}


	@Override
	public void executeTask(Long id) throws Exception {
		//PortEntity portEntity = new PortEntity();
		//List<PortEntity> portList =  portEntity.findAllPortEntity();	
		
	//解析海航、深航、国航的航班时刻表
	this.parseFLightByPDF();
	//解析南航、东航航班时刻
	this.parseFlightOnLine();
		 
	}
    
	@Transactional
	public void save(FlightInfoEntity flightEntity,FlightInfoEntity entity){
		flightEntity.save(entity);
	}
	public String getFromCity() {
		return fromCity;
	}

	public void setFromCity(String fromCity) {
		this.fromCity = fromCity;
	}

	public String getToCity() {
		return toCity;
	}

	public void setToCity(String toCity) {
		this.toCity = toCity;
	}
    
	public static synchronized void ceCount(){
		System.out.println("                 东航还剩："+(--ceairRemain));
	}
	public static synchronized void feiCount(){
		System.out.println("                还剩："+(--feiRemain));
	}
	public static synchronized void csCount(){
		System.out.println("                 南航还剩："+(--csairRemain));
	}
	public static synchronized void mfCount(){
		System.out.println("                 厦航还剩："+(--csairRemain));
	}
	
	private void parseFlightOnLine(){
		int count = 0,sum=0;
		//1获得所有机场信息
		PortEntity portEntity = new PortEntity();
		//获得所有机场
		List<PortEntity> portList =  portEntity.findAll();	
		//2循环拼装成 xxx-xxx 形式
		List<String> portCodes = new ArrayList<String>();
		for (Iterator iterator = portList.iterator(); iterator.hasNext();) {
			PortEntity portEntity1 = (PortEntity) iterator.next();
			for (Iterator iterator2 = portList.iterator(); iterator2.hasNext();) {
				PortEntity portEntity2 = (PortEntity) iterator2.next();
				portCodes.add(portEntity1.getCode()+"-"+portEntity2.getCode());
			}
		}	
		//设置线程数量
		//int threadCount = PropertyUtils.getIntProperty("crawl.thread.count", CrawlPropertiesLoader.CONFIG_FILE);
 		 //下面是东航的线程
		//开多线程去尝试
		int threadCount =10;//设置线程数量
		int count1 = portCodes.size()/threadCount;
		ExecutorService service = Executors.newFixedThreadPool(threadCount);
		 for(int i=0;i<threadCount;i++){
			 if(i==(threadCount-1)){
				 service.execute(new CELineThread(portCodes.subList(i*count1,count1*(i+1)+1)));
			 }else{
				 service.execute(new CELineThread(portCodes.subList(i*count1,count1*(i+1))));	
			 }
	     }
		 service.shutdown();
		// logger.debug("解析成功！");
		
		
		//下面是南航的线程
		//开多线程去尝试
		int threadCount2 = 10;//设置线程数量
		int count2 = portCodes.size()/threadCount2;
		ExecutorService service2 = Executors.newFixedThreadPool(threadCount2);
		 for(int i=0;i<threadCount2;i++){
			 if(i==(threadCount2-1)){
				 service2.execute(new CSAirLineThread(portCodes.subList(i*count2,count2*(i+1)+1)));
			 }else{
				 service2.execute(new CSAirLineThread(portCodes.subList(i*count2,count2*(i+1))));	
			 }
	     }
		 service2.shutdown();
		 logger.debug("解析成功！");
	}
	
	private void parseFLightByPDF() throws Exception{
		//深圳航空航班时刻表解析
		ExecutorService service = Executors.newFixedThreadPool(3);
		service.execute(new ZHLinePdfParseThread());
		
		//海南航空航班时刻表解析
		//ExecutorService service = Executors.newFixedThreadPool(3);
		service.execute(new HNLinePdfParseThread());
		
		//国航航班时刻表解析
		//国航还没完善，先注释
		//service.execute(new CALinePdfParseThread());
		
			
	}
}
